const PageHelper = require("./pageHelper");
var ph = require("./PuppeteerHelper");
var pageHelper = new PageHelper();
/**
 * 搜索速卖通,并根据价格返回结果最接近要求的价格的那个商品，如果没有价格参数，则返回第一个商品
 * @param {string} keyword 关键词
 * @param {number} price 价格(返回结果中价格与此价格相差不超过10%)
 */
async function searchAliexpress(keyword, price) {
  try {
    if (!keyword) return; //去除execl空值

    keyword = keyword.trim();
    if (global.ph == null) {
      global.ph = ph;
      await ph.init();
    }
    if (global.pageHelper == null) {
      pageHelper = new PageHelper(ph.page);
      global.pageHelper = pageHelper;
    }
    ph = global.ph;
    pageHelper = global.pageHelper;
    const minPrice = Math.round(price * 0.8);
    const maxPrice = Math.round(price * 1.2);
    const url = price
      ? `https://www.aliexpress.com/w/wholesale-${keyword}.html?catId=0&SearchText=${keyword}&minPrice=${minPrice}&maxPrice=${maxPrice}`
      : `https://www.aliexpress.com/w/wholesale-${keyword}.html?catId=0&SearchText=${keyword}`;

    // console.log(url);
    await pageHelper.page.goto(url, { waitUntil: "domcontentloaded" });
    // const InputElementName ='#search-key';
    // await pageHelper.pageLoadByElement(InputElementName);
    // await pageHelper.setInputNoType(InputElementName,keyword,'输入关键字');
    // const searchButton= await pageHelper.getElement('#form-searchbar > div.searchbar-operate-box > input');
    // await searchButton.click();
    await pageHelper.pageLoadByElement("#root"); //#card-list
    const itemList = await pageHelper.page.evaluate(() => {
      return window._dida_config_?._init_data_?.data?.data?.root?.fields?.mods
        ?.itemList?.content;
    });
    const result = {};
    resList = [];
    if (!itemList || itemList.length == 0) {
      console.log("没有找到商品");
      return;
    } else if (!price) {
      result.price = itemList[0].prices?.salePrice?.minPrice;
      result.detailUrl = `https://www.aliexpress.com${itemList[0].productDetailUrl}`;
      result.title = itemList[0].title?.displayTitle;
      return result;
    } else {
      for (const item of itemList)
        resList.push({
          price: item.prices?.salePrice?.minPrice,
          detailUrl: `https://www.aliexpress.com${item.productDetailUrl}`,
          title: item.title?.displayTitle,
        });
    }

    const closestPrice = findClosestPrice(resList, price);
    return closestPrice;
  } catch (error) {
    console.log(error);
  }
}
/**
 * 查找数组里面价格最接近的那个
 * @param {Array} itemList 要查找的数组
 * @param {Number} price 要查找的价格
 * @returns
 */
function findClosestPrice(itemList, price) {
  let closestElement = null;
  let minDifference = Infinity;

  for (let i = 0; i < itemList.length; i++) {
    const currentElement = itemList[i];
    const currentPrice = itemList[i].price ? itemList[i].price : 0;
    const difference = Math.abs(currentPrice - price);

    if (difference < minDifference) {
      minDifference = difference;
      closestElement = currentElement;
    }
  }

  return closestElement;
}
module.exports = searchAliexpress;
/**
 * 测试用例
 */
// (async () => {
//   const res = await searchAliexpress('鞋子',50);
//   console.log(res);
// })();
